package com.etooling.framework.utils;


import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;
import java.util.Collection;

public class VoToPoUtil {

	/**   */
	/**
	 * Copy properties of orig to dest Exception the Entity and Collection Type
	 * 
	 * @param vo
	 * @param po
	 * @return the dest bean
	 * @throws Exception
	 */
	public static  Object copyProperties(Object vo, Object po) throws Exception {
		if (vo == null || po == null) {
			return vo;
		}

		PropertyDescriptor[] destDesc = PropertyUtils.getPropertyDescriptors(vo);
		try {
			for (int i = 0; i < destDesc.length; i++) {
				Class destType = destDesc[i].getPropertyType();
				Class origType = PropertyUtils.getPropertyType(po, destDesc[i].getName());
				if (destType != null && destType.equals(origType) && !destType.equals(Class.class)) {
					if (!Collection.class.isAssignableFrom(origType)) {
						try {
							Object value = PropertyUtils.getProperty(po, destDesc[i].getName());
							PropertyUtils.setProperty(vo, destDesc[i].getName(), value);
						} catch (Exception ex) {
						}
					}
				}
			}

			return vo;
		} catch (Exception ex) {
			throw ex;
			// return dest;
		}
	}

	/**   */
	/**
	 * Copy properties of orig to dest Exception the Entity and Collection Type
	 * 
	 * @param po po 要保存的实体
	 * @param vo 界面传过来的
	 * @param ignores  忽略的属性。
	 * @return the dest bean
	 * @throws Exception
 
	 */
	public static Object copyProperties(Object po, Object vo, String... ignores) throws Exception {
		if (po == null || vo == null) {
			return po;
		}

		PropertyDescriptor[] destDesc = PropertyUtils.getPropertyDescriptors(po);

		for (int i = 0; i < destDesc.length; i++) {
			if (contains(ignores, destDesc[i].getName())) {
				continue;
			}

			Class destType = destDesc[i].getPropertyType();
			Class origType = PropertyUtils.getPropertyType(vo, destDesc[i].getName());
			if (destType != null && destType.equals(origType) && !destType.equals(Class.class)) {
				if (!Collection.class.isAssignableFrom(origType)) {
					Object value = PropertyUtils.getProperty(vo, destDesc[i].getName());
					PropertyUtils.setProperty(po, destDesc[i].getName(), value);
				}
			}
		}

		return po;

	}



	static boolean contains(String[] ignores, String name) {
		boolean ignored = false;
		for (int j = 0; ignores != null && j < ignores.length; j++) {
			if (ignores[j].equals(name)) {
				ignored = true;
				break;
			}
		}

		return ignored;
	}
}
